//app.js
var userUtil = require('./utils/user.js')
const api = require('./config/api.js')
import touch from './utils/touch.js'
import util from './utils/util.js';

App({
  touch: new touch(),
  
  globalData: {
    images_server_addr: 'http://image.wuduoshan.com/',
    navHeight: 0,
    userInfo: null,
    isIos: false
  },

  onLaunch: function () {
    let app = this
    wx.getSystemInfo({
      success: function (res) {
        if(res.platform === 'ios'){
          app.globalData.isIos = true
        }
        console.log('client is ios',app.globalData.isIos)
      }
    })
    
    const updateManager = wx.getUpdateManager();
    wx.getUpdateManager().onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
  },

  // 获取当前页面路径
  getCurrentPath() {
    // 加载的页面
    let pages = getCurrentPages()
    // 当前页面对象 
    let currentPage = pages[pages.length - 1]
    // 当前页面url(path)
    let path = currentPage.route
    return path
  },

  // 判断用户是否已登录
  hasLogin(callback) {
    const app = this

    let _login = false
    wx.request({
      url: api.AuthLoginCheck,
      method: 'post',
      header: {
        'X-Wds-Token': util.getStorageSync('token')
      },
      success: function (obj) {
        console.log('hasLogin obj',obj)
        if (obj.statusCode === 200) {
          // 已登录
          _login = true
        }else{
          userUtil.updateStorageUserInfo(null)
        }
      },
      complete: function () {
        typeof callback == "function" && callback(_login)
      }
    })
  },

  /**
   * 获取用户信息交给callback
   * <p>
   * 检查sessionKey是否有效，如果有效则从缓存获取用户
   */
  getUserInfo: function (callback) {
    userUtil.checkLogin().then((userInfo) => {
      console.log('app.js get userInfo',userInfo)
      if(util.isEmpty(userInfo)){
        // 未登录
        wx.navigateTo({
          url: '/pages/auth/login/login'
        })
        return
      }else{
        //存储用户信息
        let enterpriseId = util.getStorageSync('enterpriseId')
        let placeId = util.getStorageSync('placeId')
        if(!util.isEmpty(enterpriseId)){
          userInfo.enterpriseId = enterpriseId
        }

        if(!util.isEmpty(placeId)){
          userInfo.placeId = placeId
        }
        
        userUtil.updateStorageUserInfo(userInfo)
        typeof callback == "function" && callback(userInfo)
      }
    })
  }
})